package servlet;

import java.io.IOException;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import managers.PersonnesManager;
import Base.Personne;

/**
 * Servlet implementation class AuthAction
 */
public class AuthAction extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private PersonnesManager ref;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AuthAction() {
		super();
		// TODO Auto-generated constructor stub
	}

	@Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		super.init();
		Hashtable<String, String> h = new Hashtable<String, String>();
		h.put("java.naming.factory.initial",
				"org.objectweb.carol.jndi.spi.MultiOrbInitialContextFactory");
		h.put("java.naming.provider.url", "rmi://localhost:1099");
		h.put("java.naming.factory.url.pkgs", "org.objectweb.jonas.naminsg");
		Context ctx;

		try {
			ctx = new InitialContext(h);
			String JNDI_NAME = "managers.PersonnesManagerBean" + "_"
					+ PersonnesManager.class.getName() + "@Remote";
			this.ref = (PersonnesManager) ctx.lookup(JNDI_NAME);
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		Personne p = null;
		try {
			p = ref.authentif(request.getParameter("loginPersonne"),
					request.getParameter("password"));
			session.setAttribute("users", p);
			if(p != null){
				if(p.getTypePersonne() == 0){
					response.sendRedirect(response.encodeRedirectURL("portail.jsp"));
				}else{
					response.sendRedirect(response.encodeRedirectURL("portail_admin.jsp"));
				}
			}else{
				response.sendRedirect(response.encodeRedirectURL("index.jsp"));
			}
		} catch (Exception e) { 
			e.printStackTrace();
		}
		
		//request.getRequestDispatcher("formResult.jsp").forward(request,response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
